const uuidv4 = require('uuid/v4');
var crypto = require('crypto');
var fs = require('fs');
var request = require('request');
// var connectJMS = require('../jms/connect.jms');
var fileServerConfig = require('../../app.config/env/fileServer.config');
var constant = require('../common/constant');
var jms = require('../../app.config/env/jms.config');
var Stomp = require('stomp-client');
var queue = jms.merchant_queueName;

var merchantService = require('../service/merchant.service');

module.exports = {
    regist: regist,
    login: login,
    logout: logout
};

function logout(req, res, next) {
    req.session.merchant = null;
    res.json({result: true});
}

function regist(req, res, next) {
    var body = req.body;
    merchantService.findMerchantByAccount(body.account, function (err, doc) {
        var response = {};
        if (err) {
            console.log("error" + Error(err));
            response.result = false;
            response.code = constant.ServerDown;
            res.json(response);
        } else if (!doc) {
            var merchant = {};
            var md5 = crypto.createHash('md5');   //crypto模块功能是加密并生成各种散列
            merchant._id = uuidv4();
            merchant.account = body.account;
            merchant.name = body.name;
            merchant.pwd = md5.update(body.pwd).digest('hex');
            merchant.address = body.address;
            var imgHeadPath = "head/" + merchant._id + ".jpg";
            var imgCardPath = "idcard/" + merchant._id + ".jpg";
            var files = req.files;
            var cardFileName = files.imgCard.name;
            var headFileName = files.imgHead.name;
            var imgs = [];
            var idBuf = fs.readFileSync(__dirname + '/../../uploads/' + cardFileName);
            var headBuf = fs.readFileSync(__dirname + '/../../uploads/' + headFileName);
            imgs.push({filename: imgCardPath, file: idBuf.toString('base64')});
            imgs.push({filename: imgHeadPath, file: headBuf.toString('base64')});
            fs.unlink(__dirname + '/../../uploads/' + cardFileName);
            fs.unlink(__dirname + '/../../uploads/' + headFileName);
            merchant.imgHead = imgHeadPath;
            merchant.imgCard = imgCardPath;
            merchant.star = constant.Star;
            //
            merchant.status = constant.Pedding;
            ;request.post({
                url: fileServerConfig.fileServer.url,
                form: {"files": imgs}
            }, function (err, httpResponse, body) {
                if (err) {
                    response.result = false;
                    response.code = constant.ServerDown
                    res.json(response);
                } else {

                    //insect db
                    console.log("insert:" + JSON.stringify(merchant));
                    merchantService.addMerchant(merchant, function (err, doc) {
                        if (err) {
                            console.log("error" + Error(err));
                            response.result = false;
                            response.code = constant.ServerDown;
                            res.json(response);
                        } else {
                            console.log("insert success doc:" + doc);
                            response.result = true;
                            response.obj = doc;
                            var protocol = {
                                result: true,
                                data: doc
                            }
                            var connectJMS = new Stomp(jms.host, jms.port, jms.username, jms.password);
                            connectJMS.destination = queue;
                            connectJMS.connect(function () {
                                connectJMS.publish(connectJMS.destination, JSON.stringify(protocol));
                                connectJMS.disconnect();
                            });
                            res.json(response);
                        }


                    })
                }

            });
        } else {
            response.result = false;
            response.code = constant.AccountExit;
            res.json(response);
        }

    });

    console.log("regist end");
}


function login(req, res, next) {
    var md5 = crypto.createHash('md5');
    var account = req.params.account;
    var en_pwd = md5.update(req.params.pwd).digest('hex');
    console.log("account:" + account + ",en_pwd:" + en_pwd);
    var response = {};
    merchantService.findMerchantByAccount(account, function (err, doc) {
        if (err) {
            console.log("error" + Error(err));
            response.result = false;
            response.code = constant.ServerDown;
            res.json(response);
        } else {
            if (doc) {
                var dbPwd = doc.pwd;
                if (en_pwd == dbPwd) {
                    response.result = true;
                    response.obj = doc;
                    req.session.merchant = doc;
                    res.json(response);
                } else {
                    response.result = false;
                    response.code = constant.PasswordError;
                    res.json(response);
                }
            } else {
                response.result = false;
                response.code = constant.AccountNoExit;
                res.json(response);
            }
        }
    });
    console.log('end');

}